import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/epidemic/area_picker.dart';
import 'package:flutter_syt/domain/widgets/common_dialog.dart';
import 'package:flutter_syt/domain/widgets/custom_dialog.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "epidemicForm")
class EpidemicForm extends StatefulWidget {
  final String? id;
  final String? add; // 补卡

  EpidemicForm({this.id, this.add});

  @override
  _EpidemicFormState createState() => _EpidemicFormState();
}

class _EpidemicFormState extends State<EpidemicForm> {
  final _formKey = GlobalKey<FormState>();
  final FocusNode focusNode = FocusNode();
  var formSetting;

  bool _checkboxSelected = false;
  bool _isDetail = false;
  var userInfo;
  var form_id;

  @override
  void initState() {
    formSetting = [];
    _getFormInfo(widget.id);
    _initUserInfo();
    super.initState();
  }

  Future _initUserInfo() async {
    userInfo = UserInfo.me.cert;
    print(userInfo?.license_number != '');
    setState(() {
      userInfo = userInfo;
    });
  }

  Future _getFormInfo(id) async {
    if (id == null || id == 'null') {
      formSetting = await API.shared.epidemic.form();
      setState(() {
        form_id = formSetting.form_id;
        formSetting = formSetting.form;
      });
    } else {
      _checkboxSelected = true;
      _isDetail = true;
      formSetting = await API.shared.epidemic.reportDetail(widget.id!);
      setState(() {
        formSetting = formSetting;
      });
    }
  }

  Future _report() async {
    // // 上传图片
    // formSetting.forEach((item) async {
    //   if (item.type == '8') {
    //     List<String> urls = [];
    //     for (var item in item.value) {
    //       var result = await API.shared.common.uploadImage(item.path);
    //       urls.add(result.url);
    //     }
    //     item.value = urls;
    //   }
    // });
    print(widget.add);
    if (widget.add != null) {
      await API.shared.epidemic.report(
        form_id,
        '${widget.add}',
        formSetting,
      );
    } else {
      await API.shared.epidemic.report(
        form_id,
        '',
        formSetting,
      );
    }
  }

  Future _submit() async {
    final form = _formKey.currentState;
    if (form!.validate()) {
      await loading(_report, text: S.of(context).submitting);
      customShowToast(S.of(context).submit_success);
      Navigator.of(context).popUntil((route) => route.isFirst);
      RouteManager.push(context, RoutMapping.epidemicPage());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          S.of(context).covid_19,
        ),
      ),
      body: SafeArea(
        child: GestureDetector(
          onTap: ClickUtils.debounce(() {
            focusNode.unfocus();
          }),
          child: ListView(
            children: [
              Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  color: ThemeColor.bkColorFFFFFF,
                ),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      userInfo?.name != ''
                          ? Container(
                              padding: EdgeInsets.all(15),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    S.of(context).basic_info,
                                    style: TextStyle(
                                      fontSize: 20,
                                      color: ThemeColor.colorBlack100,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 20),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          S.of(context).name,
                                          style: TextStyle(
                                            fontSize: 16,
                                            color: ThemeColor.colorBlack60,
                                          ),
                                        ),
                                        Text(
                                          userInfo?.name ?? '',
                                          style: TextStyle(
                                            fontSize: 16,
                                            color: ThemeColor.colorBlack100,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 20),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          S.of(context).id_number,
                                          style: TextStyle(
                                            fontSize: 16,
                                            color: ThemeColor.colorBlack60,
                                          ),
                                        ),
                                        Text(
                                          userInfo?.license_number ?? '',
                                          style: TextStyle(
                                            fontSize: 16,
                                            color: ThemeColor.colorBlack100,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            )
                          : Container(),
                      userInfo?.name != ''
                          ? Container(
                              height: 10,
                              decoration: BoxDecoration(
                                color: ThemeColor.bkColorF8F8F8,
                              ),
                            )
                          : Container(),
                      Container(
                        padding: userInfo?.name != ''
                            ? EdgeInsets.all(15)
                            : EdgeInsets.fromLTRB(15, 0, 15, 15),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              S.of(context).submit_health_information,
                              style: TextStyle(
                                fontSize: 20,
                                color: ThemeColor.colorBlack100,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            ...formSetting.map((item) {
                              return Container(
                                margin: EdgeInsets.only(top: 20),
                                child: _formItem(item),
                              );
                            }).toList(),
                          ],
                        ),
                      ),
                      !_isDetail
                          ? Container(
                              padding: EdgeInsets.fromLTRB(0, 15, 15, 15),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Checkbox(
                                    value: _checkboxSelected,
                                    activeColor: ThemeColor.primaryColor,
                                    checkColor: Colors.black,
                                    onChanged: (value) {
                                      if (_isDetail) {
                                        return;
                                      }
                                      setState(() {
                                        _checkboxSelected = !_checkboxSelected;
                                      });
                                    },
                                  ),
                                  Expanded(
                                    child: Text(
                                      S.of(context).Exemption_content,
                                      softWrap: true,
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: ThemeColor.colorBlack40,
                                        fontWeight: FontWeight.w300,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            )
                          : Text(''),
                      // !_isDetail
                      //     ? Padding(
                      //         padding: EdgeInsets.only(left: 50),
                      //         child: Column(
                      //           crossAxisAlignment: CrossAxisAlignment.start,
                      //           children: [
                      //             Container(
                      //               width: 12,
                      //               height: 0,
                      //               margin: EdgeInsets.only(left: 10),
                      //               decoration: new BoxDecoration(
                      //                 border: Border(
                      //                   // 四个值 top right bottom left
                      //                   bottom: BorderSide(
                      //                       color: ThemeColor.colorBlack80,
                      //                       width: 5,
                      //                       style: BorderStyle.solid),
                      //                   right: BorderSide(
                      //                       color: Colors.transparent,
                      //                       width: 6,
                      //                       style: BorderStyle.solid),
                      //                   left: BorderSide(
                      //                       color: Colors.transparent,
                      //                       width: 6,
                      //                       style: BorderStyle.solid),
                      //                 ),
                      //               ),
                      //             ),
                      //             Container(
                      //               alignment: Alignment.center,
                      //               width: 180,
                      //               height: 30,
                      //               // padding: EdgeInsets.all(14),
                      //               decoration: BoxDecoration(
                      //                 color: ThemeColor.colorBlack80,
                      //                 borderRadius: BorderRadius.circular(4),
                      //               ),
                      //               child: Text(
                      //                 '请先阅读并勾选此承若后提交',
                      //                 style: TextStyle(
                      //                   color: Colors.white,
                      //                   fontSize: 12,
                      //                 ),
                      //               ),
                      //             ),
                      //           ],
                      //         ),
                      //       )
                      //     : Text(''),
                      Divider(
                        color: ThemeColor.dividerColor,
                      ),
                      !_isDetail
                          ? Padding(
                              padding: EdgeInsets.fromLTRB(15, 8, 15, 36),
                              child: ElevatedButton(
                                  style: (!_checkboxSelected || _isDetail)
                                      ? ElevatedButton.styleFrom(
                                          // onPrimary: Color(0xffdedede),
                                          // primary: Color(0xffdedede),
                                        )
                                      : null,
                                  child: Text(
                                    S.of(context).submit,
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold,
                                      color: ThemeColor.colorBlack100,
                                    ),
                                  ),
                                  onPressed: ClickUtils.debounce(
                                    () async {
                                      if (!_checkboxSelected) {
                                        return null;
                                      }
                                      if (_isDetail) {
                                        return null;
                                      }
                                      final form = _formKey.currentState;
                                      if (form!.validate()) {
                                        showCommonDialog(
                                          context,
                                          DialogEntity(
                                            '',
                                            Container(
                                              padding: EdgeInsets.only(
                                                  bottom: 30,
                                                  left: 25,
                                                  right: 25),
                                              child: Text(
                                                S.of(context).check_prompt,
                                                style: FontStyles
                                                    .headerTextStyle_14,
                                              ),
                                            ),
                                            () {
                                              Navigator.of(context).pop();
                                            },
                                            () async {
                                              _submit();
                                            },
                                            okText: S.of(context).confirm,
                                            cancelText: S.of(context).cancel,
                                            contentPadding:
                                                EdgeInsets.only(bottom: 0),
                                          ),
                                        );
                                      }
                                    },
                                  )),
                            )
                          : Text(''),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _formItem(formData) {
    switch (formData.type) {
      case '1':
        return TextFormField(
          enableInteractiveSelection: true,
          enabled: !_isDetail,
          inputFormatters: [
            FilteringTextInputFormatter.deny(appContext.emojiRegexp)
          ],
          validator: (value) {
            if (formData.validate.required == '1' &&
                (value == null || value.isEmpty)) {
              return '值不能为空';
            }
            return null;
          },
          initialValue: formData.value,
          maxLines: 1,
          decoration: InputDecoration(
            labelText: formData.name,
            hintText: formData.placeholder,
            labelStyle: TextStyle(
              color: ThemeColor.colorBlack60,
              fontSize: 22,
            ),
            hintStyle: TextStyle(
              color: ThemeColor.colorBlack30,
              fontSize: 16,
            ),
            floatingLabelBehavior: FloatingLabelBehavior.always,
          ),
          onChanged: (value) {
            formData.value = value;
          },
          onSaved: (value) {
            formData.value = value;
          },
          // 当用户确定已经完成编辑时触发
          onFieldSubmitted: (value) {
            formData.value = value;
          },
        );
        break;

      case '2':
        return TextFormField(
          enableInteractiveSelection: true,
          enabled: !_isDetail,
          inputFormatters: [
            FilteringTextInputFormatter.deny(appContext.emojiRegexp)
          ],
          keyboardType: TextInputType.multiline,
          minLines: 1,
          maxLines: 5,
          validator: (value) {
            if (formData.validate.required == '1' &&
                (value == null || value.isEmpty)) {
              return '值不能为空';
            }
            return null;
          },
          initialValue: formData.value,
          decoration: InputDecoration(
            labelText: formData.name,
            hintText: formData.placeholder,
            labelStyle: TextStyle(
              color: ThemeColor.colorBlack60,
              fontSize: 22,
            ),
            hintStyle: TextStyle(
              color: ThemeColor.colorBlack30,
              fontSize: 16,
            ),
            floatingLabelBehavior: FloatingLabelBehavior.always,
          ),
          onChanged: (value) {
            formData.value = value;
          },
          onSaved: (value) {
            formData.value = value;
          },
          // 当用户确定已经完成编辑时触发
          onFieldSubmitted: (value) {
            formData.value = value;
          },
        );
        break;
      case '3':
        return TextFormField(
          enableInteractiveSelection: true,
          enabled: !_isDetail,
          inputFormatters: [
            FilteringTextInputFormatter.deny(appContext.emojiRegexp)
          ],
          validator: (value) {
            if (formData.validate.required == '1' &&
                (value == null || value.isEmpty)) {
              return '值不能为空';
            }
            return null;
          },
          initialValue: formData.value,
          focusNode: focusNode,
          keyboardType: TextInputType.numberWithOptions(decimal: true),
          decoration: InputDecoration(
            labelText: formData.name,
            hintText: formData.placeholder,
            labelStyle: TextStyle(
              color: ThemeColor.colorBlack60,
              fontSize: 22,
            ),
            hintStyle: TextStyle(
              color: ThemeColor.colorBlack30,
              fontSize: 16,
            ),
            floatingLabelBehavior: FloatingLabelBehavior.always,
          ),
          onChanged: (value) {
            formData.value = value;
          },
          onSaved: (value) {
            formData.value = value;
          },
          // 当用户确定已经完成编辑时触发
          onFieldSubmitted: (value) {
            formData.value = value;
          },
        );
        break;
      case '4':
        if (formData.value == null) {
          formData.value = formData.opt[0];
        }
        return _isDetail
            ? Column(
                children: [
                  Row(
                    children: [
                      Flexible(
                          child: Text(
                        formData.name,
                        style: TextStyle(
                          color: ThemeColor.colorBlack60,
                          fontSize: 16,
                          fontFamily: 'PingFang SC',
                        ),
                        textAlign: TextAlign.left,
                        maxLines: 2,
                      ))
                    ],
                  ),
                  TextFormField(
                    enableInteractiveSelection: true,
                    enabled: !_isDetail,
                    initialValue: formData.value,
                    maxLines: 1,
                    inputFormatters: [
                      FilteringTextInputFormatter.deny(appContext.emojiRegexp)
                    ],
                    decoration: InputDecoration(
                      hintText: formData.placeholder,
                      hintStyle: TextStyle(
                        color: ThemeColor.colorBlack30,
                        fontSize: 16,
                      ),
                      floatingLabelBehavior: FloatingLabelBehavior.always,
                    ),
                  )
                ],
              )
            // TextFormField(
            //         enabled: !_isDetail,
            //         initialValue: '初始化',
            //         maxLines: 1,
            //         decoration: InputDecoration(
            //           labelText: formData.name,
            //           hintText: formData.placeholder,
            //           labelStyle: TextStyle(
            //             color: ThemeColor.colorBlack60,
            //             fontSize: 22,
            //           ),
            //           hintStyle: TextStyle(
            //             color: ThemeColor.colorBlack30,
            //             fontSize: 16,
            //           ),
            //           floatingLabelBehavior: FloatingLabelBehavior.always,
            //         ),
            //       )
            : Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    formData.name,
                    style: TextStyle(
                      color: ThemeColor.colorBlack60,
                      fontSize: 16,
                    ),
                  ),
                  ...formData.opt.map<Widget>((item) {
                    return Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Radio(
                          visualDensity: VisualDensity(horizontal: -4),
                          value: '$item',
                          onChanged: (value) {
                            print('1111');
                            print(value);
                            formData.value = value;
                            setState(() {});
                          },
                          // 按钮组的值
                          groupValue: formData.value,
                        ),
                        Text('$item'),
                      ],
                    );
                  }).toList(),
                ],
              );
        // DropdownButtonFormField(
        //     validator: (value) {
        //       if (formData.validate.required == '1' && (value == null)) {
        //         return '值不能为空';
        //       }
        //       return null;
        //     },
        //     icon: Icon(
        //       Icons.chevron_right,
        //       color: ThemeColor.colorBlack60,
        //     ),
        //     value: formData?.value,
        //     items: formData.opt.map<DropdownMenuItem<Object>>((label) {
        //       return DropdownMenuItem(
        //         child: Text(label),
        //         value: label,
        //       );
        //     }).toList(),
        //     onChanged: _isDetail
        //         ? null
        //         : (value) {
        //             if (_isDetail) {
        //               return null;
        //             }
        //             formData.value = value;
        //           },
        //     decoration: InputDecoration(
        //       labelText: formData.name,
        //       hintText: formData.placeholder,
        //       labelStyle: TextStyle(
        //         color: ThemeColor.colorBlack60,
        //         fontSize: 22,
        //       ),
        //       hintStyle: TextStyle(
        //         color: ThemeColor.colorBlack30,
        //         fontSize: 16,
        //       ),
        //       floatingLabelBehavior: FloatingLabelBehavior.always,
        //     ),
        //   );
        break;
      case '5':
        if (formData.value == null) {
          formData.value = formData.opt[0];
        }
        return _isDetail
            ? TextFormField(
                enableInteractiveSelection: true,
                enabled: !_isDetail,
                inputFormatters: [
                  FilteringTextInputFormatter.deny(appContext.emojiRegexp)
                ],
                initialValue: formData.value,
                maxLines: 1,
                decoration: InputDecoration(
                  labelText: formData.name,
                  hintText: formData.placeholder,
                  labelStyle: TextStyle(
                    color: ThemeColor.colorBlack60,
                    fontSize: 22,
                  ),
                  hintStyle: TextStyle(
                    color: ThemeColor.colorBlack30,
                    fontSize: 16,
                  ),
                  floatingLabelBehavior: FloatingLabelBehavior.always,
                ),
              )
            : Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    formData.name,
                    style: TextStyle(
                      color: ThemeColor.colorBlack60,
                      fontSize: 16,
                    ),
                  ),
                  ...formData.opt.map<Widget>((item) {
                    return Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Checkbox(
                          visualDensity: VisualDensity(horizontal: -4),
                          value: formData.value != null
                              ? formData.value.split(' ').indexOf(item) > -1
                              : false,
                          onChanged: (value) {
                            print(value);
                            List selectData = formData.value?.split(' ') ?? [];
                            if (selectData.indexOf(item) > -1) {
                              selectData.remove(item);
                            } else {
                              selectData.add(item);
                            }
                            print(selectData);
                            formData.value = selectData.join(' ');
                            setState(() {});
                          },
                        ),
                        Text('$item'),
                      ],
                    );
                  }).toList(),
                ],
              );
        // MultiplePicker(
        //     MultiplePickerItemEntity(
        //       formData.name,
        //       formData.placeholder,
        //       formData.value == null ? '' : formData.value,
        //       formData.opt,
        //       (value) {
        //         formData.value = value;
        //         setState(() {});
        //       },
        //     ),
        //   );
        break;
      case '6':
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              formData.name,
              style: TextStyle(
                color: ThemeColor.colorBlack60,
                fontSize: 16,
              ),
            ),
            GestureDetector(
              onTap: ClickUtils.debounce(() async {
                if (_isDetail) {
                  return;
                }
                var result = await showDatePicker(
                  context: context,
                  initialDate: DateTime.now(),
                  firstDate: DateTime(2020),
                  lastDate: DateTime(2026),
                );
                formData.value = result.toString().split(' ')[0];
                setState(() {});
              }),
              child: Container(
                padding: EdgeInsets.only(top: 6, bottom: 10),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: formData.value != null
                        ? BorderSide(width: 1, color: Color(0xffDFDFDF))
                        : BorderSide(width: 2, color: Color(0xffc6c6c6)),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      formData.value == null
                          ? formData.placeholder
                          : formData.value,
                      style: TextStyle(
                        color: formData.value != null
                            ? ThemeColor.colorBlack80
                            : ThemeColor.colorBlack30,
                        fontSize: 16,
                      ),
                    ),
                    _isDetail
                        ? Container()
                        : Icon(
                            Icons.chevron_right,
                            color: formData.value != null
                                ? ThemeColor.colorBlack30
                                : ThemeColor.colorBlack60,
                          ),
                  ],
                ),
              ),
            ),
          ],
        );
        break;
      // case '8':
      //   // TODO:图片上传 详情直接查看
      //   return Container(
      //     margin: EdgeInsets.symmetric(vertical: 10.0),
      //     alignment: Alignment.topLeft,
      //     child: Column(
      //       crossAxisAlignment: CrossAxisAlignment.start,
      //       children: [
      //         Text(
      //           formData.name,
      //           style: FontStyles.headerTextStyle_16.copyWith(
      //             color: ThemeColor.colorBlack80,
      //             fontWeight: FontWeight.w400,
      //           ),
      //         ),
      //         Container(
      //           margin: EdgeInsets.symmetric(vertical: 15.0),
      //           child: ImageUpload(
      //             maxLength: 1,
      //             width: 95,
      //             height: 95,
      //             images: formData.value != null ? formData.value : [],
      //             onChange: (newImages) {
      //               // List<String> urls = [];
      //               // for (var item in newImages) {
      //               //   var result =
      //               //       await API.shared.common.uploadImage(item.path);
      //               //   urls.add(result.url);
      //               // }
      //               // formData.value = urls.toString();
      //               formData.value = newImages;
      //               setState(() {});
      //             },
      //           ),
      //         ),
      //       ],
      //     ),
      //   );
      //   break;
      case '10':
        return _isDetail
            ? Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Text(
                  formData.name,
                  style: TextStyle(
                    color: ThemeColor.colorBlack60,
                    fontSize: 16,
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(top: 6, bottom: 10),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(width: 1, color: Color(0xffdfdfdf)),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        formData.value,
                        style: TextStyle(
                          color: ThemeColor.colorBlack80,
                          fontSize: 16,
                        ),
                      ),
                    ],
                  ),
                ),
              ])
            : AreaPicker(PickerItemEntity(
                formData.name,
                formData.placeholder,
                (value) {
                  print(value);
                  formData.value = value;
                },
              ));
        break;
      default:
        return Text('');
        break;
    }
  }
}
